package com.example.common.exception;

import cn.hutool.core.collection.CollectionUtil;
import com.example.common.enums.ResultCode;
import com.example.common.resp.GlobalResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@Slf4j
@RestControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionHandler {

    /**
     * GlobalExceptionHandler的作用是用来捕获指定的异常
     * 这里示例 捕获 Java的validation做入参的校验 的校验失败的异常
     * 统一处理，免得直接返回前端
     *
     * @param e
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public GlobalResult handleException(MethodArgumentNotValidException e) {
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        StringBuilder messages = new StringBuilder();
        if (CollectionUtil.isNotEmpty(errors)) {
            errors.stream().forEach(i -> messages.append(i.getDefaultMessage()).append(";"));
        }
        return GlobalResult.error(ResultCode.CMN_ILLEGAL_ARG.getCode(), messages.toString());
    }

    @ExceptionHandler(ServiceException.class)
    public GlobalResult handleException(ServiceException e) {
        return GlobalResult.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(value = Exception.class)
    public GlobalResult handleException(Exception e) {
        log.error(e.getMessage());
        return GlobalResult.error(ResultCode.SYS_ERROR.getCode(), e.getMessage());
    }
}

